﻿using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.WindowsAPICodePack.Shell;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using ZhuXingFamilys.Help;
using RevitAddInDeployer;

namespace ZhuXingFamilys.Fileupload
{
    /// <summary>
    /// FileUpload.xaml 的交互逻辑
    /// </summary>
    public partial class FileUpload : Window
    {
        ObservableCollection<Fileuploadinfo> ListListViewItem { get; set; }
        public FileUpload()
        {
            ColorZoneAssist.SetMode(new GroupBox(), ColorZoneMode.Light);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4), System.Windows.Media.Color.FromArgb(1, 5, 6, 7));
            InitializeComponent();
            try
            {
                string path = Set.getaddress();
                string paths = System.IO.Path.Combine(path.Substring(0, path.Length ), "image\\上传云.ico");
                Uri Icon = new Uri(paths, UriKind.Absolute);
                this.Icon = BitmapFrame.Create(Icon);
            }
            finally { }
            //uploadLoadFamily = new UploadLoadFamily();
            //externalEvent = ExternalEvent.Create(uploadLoadFamily);

        }

        //UploadLoadFamily uploadLoadFamily = null;
        //ExternalEvent externalEvent = null;
        //List<Fileuploadinfo> ListListViewItem;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialogs = new Microsoft.Win32.OpenFileDialog()
            { 
            Filter = "族文件|*.rfa"
            };
            openFileDialogs.Multiselect = true;
            var result = openFileDialogs.ShowDialog();
            if (result == false)
            {
                return;
            }

            if (result == true)
            { /*for(openFileDialogs.count)*/
                for (int i = 0; i < openFileDialogs.FileNames.Length; i++)
                {
                    //MessageBox.Show(openFileDialogs.FileNames[i]);

                string filefullpath = openFileDialogs.FileName;
                string familyname = openFileDialogs.SafeFileName.Replace(".rfa","");


                    ShellObject so = ShellFile.FromFilePath(filefullpath);
                    Bitmap bm2 = so.Thumbnail.LargeBitmap;
                    
                    //ListListViewItem = new ObservableCollection<Fileuploadinfo>();
                    //ListListViewItem.Add(new Fileuploadinfo() { FamilyNmae = "任务1", IsChecked = false });
                    //ListListViewItem.Add(new Fileuploadinfo() { FamilyNmae = "任务2", IsChecked = true });

                    //FileUploadList.DataContext = ListListViewItem;
                    //FileUploadList.Items.Add(new { FamilyNmae = familyname, IsChecked = true, FamilyFileCategory = "测试族", RevitVersion = "2021", familyimage = ChangeBitmapToImageSource(bm2) });
                    ListListViewItem = new ObservableCollection<Fileuploadinfo>
                    {
                        new Fileuploadinfo() { FamilyNmae = familyname,familyfullpath=filefullpath, IsChecked = true, FamilyFileCategory = "测试族", RevitVersion = "2021", Familyimage = ChangeBitmapToImageSource(bm2) }
                    };
                    //ListListViewItem.AddRange();
                    FileUploadList.Items.Add(ListListViewItem);
                }
            }
        }



        //Bitmap转化为ImageSource
        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {

            //Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(

                hBitmap,

                IntPtr.Zero,

                System.Windows.Int32Rect.Empty,

                BitmapSizeOptions.FromEmptyOptions());

            return wpfBitmap;

        }

        //开始上传、插入数据库、上传族文件到服务器
        private static string SqlServerConnString = Properties.Resource.DBConnect;
        SqlConnection conn = new SqlConnection(SqlServerConnString);
        //public string username ="admin";
        private void Upload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (ObservableCollection<Fileuploadinfo> data in FileUploadList.Items)
                {
                    if (data[0].IsChecked == true)
                    {
                        try
                        {
                            UserName = Get_Username();
                            FtpHelper.Upload(data[0].familyfullpath, data[0].FamilyNmae, UserName, false);

                            string insertstring = "insert into Family_Upload values('" + data[0].FamilyNmae + "','" + UserName + "','" + data[0].RevitVersion + "','" + data[0].FamilyFileCategory + "' ,'" + DateTime.Now + "')";
                            SqlCommand sqlInsert = new SqlCommand(insertstring, conn);
                            conn.Open();
                            sqlInsert.ExecuteNonQuery();    //插入数据

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "error");
                        }
                        finally
                        {
                            conn.Close();
                           
                        }

                    }
                }
                MessageBox.Show("上传成功");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "error");
            }
            finally
            {
               
                conn.Dispose();
            }
            
        }
       
        public const string CONFIG_LOGIN_CONTENT = "LoginInfo";
        public const string CONFIG_LOGIN_USERNAME_CONTENT = "UserName";
        public static string UserName;
        //当前用户名
        public string Get_Username() {
            string iniFilePath = "LoginInfo.ini";
            string CurAppDir = Set.getaddress();
            if (!iniFilePath.Contains("\\") || !System.IO.Path.IsPathRooted(iniFilePath))
            {
                iniFilePath = System.IO.Path.Combine(CurAppDir, iniFilePath);
            }
            UserName = Set.GetValue(CONFIG_LOGIN_CONTENT, CONFIG_LOGIN_USERNAME_CONTENT, iniFilePath, out string usernamevalue);
            return UserName;
        }
       


        private void SelectAll_Checked(object sender, RoutedEventArgs e)
        {
            //Emp emp = FileUploadList.SelectedItem as Emp;
            foreach (ObservableCollection<Fileuploadinfo> data in FileUploadList.Items)
            {
                data[0].IsChecked = true;
            }
        }

        private void SelectAll_Unchecked(object sender, RoutedEventArgs e)
        {
            foreach (ObservableCollection<Fileuploadinfo> data in FileUploadList.Items)
            {
                data[0].IsChecked = false;
            }
        }

 
    

    }
}
